package com.free.front.util;

import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
public class Mu {
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/

    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(Mu.class);

    /**
     * 判断是否为非空
     *
     * @param str
     * @return
     */
    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    /**
     * 判断是否为空
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 处理String参数
     *
     * @param str
     * @return
     */
    public static String ckStr(String str) {
        if (isNotBlank(str)) {
            return str.trim();
        }
        return null;
    }

    /**
     * 处理String参数
     *
     * @param str
     * @return
     */
    public static String ckStr(String str, boolean filter) {
        if (isNotBlank(str)) {
            if (filter) {
                return str.trim().replaceAll("<", "&lt;").replaceAll(">", "&gt;");
            } else {
                return str.trim();
            }

        }
        return null;
    }

    /**
     * 处理int参数
     *
     * @param str
     * @return
     */
    public static Integer ckInt(String str) {
        if (isBlank(str)) {
            return null;
        }
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 处理long参数
     *
     * @param str
     * @return
     */
    public static Long ckLong(String str) {
        if (isBlank(str)) {
            return null;
        }
        try {
            return Long.parseLong(str.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 处理float参数
     *
     * @param str
     * @return
     */
    public static Float ckFloat(String str) {
        if (isBlank(str)) {
            return null;
        }
        try {
            return Float.valueOf(str.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 处理Bigdecimal参数
     *
     * @param str
     * @return
     */
    public static BigDecimal ckDecimal(String str) {
        if (isBlank(str)) {
            return null;
        }
        try {
            return new BigDecimal(str);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 处理成Timestamp类型
     *
     * @param str
     * @return
     */
    public static Timestamp ckTime(String str) {
        if (isBlank(str) || str.indexOf("null") != -1 || str.startsWith(" ")) {
            return null;
        }
        try {
            return Timestamp.valueOf(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 处理成Boolean型
     *
     * @param str
     * @return
     */
    public static Boolean ckBoolean(String str) {
        if (isBlank(str)) {
            return null;
        }
        if ("1".equals(str)) {
            return true;
        }
        if ("0".equals(str)) {
            return false;
        }
        try {
            return Boolean.valueOf(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 处理成Double型
     *
     * @param str
     * @return
     */
    public static Double ckDouble(String str) {
        if (isBlank(str)) {
            return null;
        }
        try {
            return Double.valueOf(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 是否包含
     *
     * @param source
     * @param arr
     * @return
     */
    public static boolean ckContain(String source, String... arr) {
        if (source == null) {
            return false;
        }
        for (String str : arr) {
            if (source.equals(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 处理字符串拼接成的数组
     *
     * @param str
     * @param regex
     * @return
     */
    public static String ckArrStr(String str, String regex, boolean wrapSplit) {
        if (StringUtils.isNotBlank(str)) {
            try {
                String[] arr = str.split(regex);
                StringBuilder sb = new StringBuilder();
                for (String s : arr) {
                    if (StringUtils.isNotBlank(s)) {
                        sb.append(s).append(regex);
                    }
                }
                if (sb.length() > 0) {
                    if (wrapSplit) {
                        return regex + sb.toString();
                    } else {
                        return sb.toString().substring(0, sb.length() - 1);
                    }
                }
            } catch (Exception e) {
                LOG.error("check Array String error: ", e);
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> ckArr(String str, String regex, Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        if (StringUtils.isNotBlank(str)) {
            try {
                String[] arr = str.split(regex);
                for (String s : arr) {
                    if (StringUtils.isNotBlank(s)) {
                        if (clazz == String.class) {
                            list.add((T) s);
                        }
                        if (clazz == Integer.class) {
                            list.add((T) Integer.valueOf(s));
                        }
                        if (clazz == Long.class) {
                            list.add((T) Long.valueOf(s));
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("check Array error: ", e);
            }
        }
        return list;
    }

    /**
     * xml输出时处理
     *
     * @param str
     * @return
     */
    public static Object xmlStr(Object str) {
        return str == null ? "" : str;
    }

    /**
     * 替换标签符号[用于存储在页面显示的字符串]
     *
     * @param str
     * @return
     */
    public static String repTagStr(String str) {
        if (str != null) {
            str = str.replaceAll("<", "《");
            str = str.replaceAll(">", "》");
            str = str.replace("&", "&amp;");
        }
        return str;
    }

    /**
     * 替换标签符号[用户替换Xml里的tag标签]
     *
     * @param str
     * @return
     */
    public static String repTagXml(String str) {
        if (str != null) {
            str = str.replaceAll("&", "&amp;");
            str = str.replaceAll("<", "&lt;");
            str = str.replaceAll(">", "&gt;");
            str = str.replaceAll("'", "&apos;");
            str = str.replaceAll("\"", "&quot;");
        }
        return str;
    }

    /**
     * 格式化：yyyy-MM-dd HH:mm:ss
     */
    public static final SimpleDateFormat dtmFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 格式化：yyyy-MM-dd HH:mm
     */

    public static final SimpleDateFormat minFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    /**
     * 格式化：M月d日H时m分
     */
    public static final SimpleDateFormat cn1Format = new SimpleDateFormat("M月d日H时m分");

    /**
     * 格式化：yyyy-MM-dd
     */
    public static final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 格式化：yyyy/MM/dd
     */
    public static final SimpleDateFormat dayFormatE = new SimpleDateFormat("yyyy/MM/dd");

    /**
     * 格式化：M月d日
     */
    public static final SimpleDateFormat dayFormatA = new SimpleDateFormat("M月d日");

    /**
     * 格式化：MM-dd
     */
    public static final SimpleDateFormat dayFormatB = new SimpleDateFormat("MM-dd");

    /**
     * 格式化：yyyyMMdd
     */
    public static final SimpleDateFormat dayFormatN_ = new SimpleDateFormat("yyyyMMdd");

    /**
     * 格式化：yyMMdd
     */
    public static final SimpleDateFormat dayFormatR = new SimpleDateFormat("yyMMdd");

    /**
     * 格式化：MM.dd
     */
    public static final SimpleDateFormat dayFormat2 = new SimpleDateFormat("MM.dd");

    /**
     * 格式化：yyyyMM
     */
    public static final SimpleDateFormat pathFormat = new SimpleDateFormat("yyyyMM");

    /**
     * 格式化：0.0
     */
    public static final DecimalFormat df0 = new DecimalFormat("0");

    /**
     * 格式化：0.0
     */
    public static final DecimalFormat df1 = new DecimalFormat("0.0");

    /**
     * 格式化：0.00
     */
    public static final DecimalFormat df2 = new DecimalFormat("0.00");

    /**
     * 格式化： 0.000000
     */
    public static final DecimalFormat df6 = new DecimalFormat("0.000000");

    /**
     * 格式化：0000
     */
    public static final DecimalFormat int4 = new DecimalFormat("0000");

    /**
     * 格式化：00
     */
    public static final DecimalFormat int2 = new DecimalFormat("00");

    /**
     * 获取操作员IP
     *
     * @param request
     * @return
     */
    public static String getIP(HttpServletRequest request) {
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        return IP;
    }

    /**
     *
     * 功能描述: <br>
     * 分割字符串
     *
     * @param str
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static List<String> splitStr(String str, String splitSign) {
        List<String> list = new ArrayList<String>();
        if (StringUtils.isNotBlank(str)) {
            String[] arr = str.split(splitSign);
            for (String img : arr) {
                if (StringUtils.isNotBlank(img)) {
                    list.add(img);
                }
            }
        }
        return list;
    }

    /** 排序商品参数 */
    public static String paramSort(String str) {
        // System.out.println("处理前：" + str);
        try {
            Map<String, String> SIZE_MAP = new LinkedHashMap<String, String>();
            SIZE_MAP.put("XXS", null);
            SIZE_MAP.put("XS", null);
            SIZE_MAP.put("S", null);
            SIZE_MAP.put("M", null);
            SIZE_MAP.put("L", null);
            SIZE_MAP.put("XL", null);
            SIZE_MAP.put("XXL", null);
            SIZE_MAP.put("2XL", null);
            SIZE_MAP.put("XXXL", null);
            SIZE_MAP.put("3XL", null);
            SIZE_MAP.put("XXXXL", null);
            SIZE_MAP.put("4XL", null);

            String[] arr = str.split(",");
            int n = 0;
            Boolean have;
            String asUpperCase;
            StringBuilder outLess = new StringBuilder();
            for (String as : arr) {
                have = false;
                for (Map.Entry<String, String> sm : SIZE_MAP.entrySet()) {
                    asUpperCase = as.toUpperCase();
                    if (asUpperCase.startsWith(sm.getKey())) {
                        sm.setValue(as);
                        n++;
                        have = true;
                        break;
                    }
                }
                if (!have) {
                    outLess.append(as);
                    outLess.append(",");
                }
            }

            if (n > arr.length / 2) {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, String> sm : SIZE_MAP.entrySet()) {
                    if (StringUtils.isNotBlank(sm.getValue())) {
                        sb.append(sm.getValue());
                        sb.append(",");
                    }
                }
                // System.out.println("----------------------------------------------------------");
                // System.out.println("处理后：" + sb.toString() +
                // outLess.toString());
                return sb.append(outLess).toString();
            } else {
                // System.out.println("未处理");
                return str;
            }
        } catch (Exception e) {
            LOG.error("排序商品参数异常", e);
            // System.out.println("处理失败");
            return str;
        }
    }

    /** 判断是不是ajax请求 */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(header) ? true : false;
    }

    /** 是否正常的请求 */
    public static boolean isNormalRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return header != null ? true : false;
    }

    public static BigDecimal bd1000 = new BigDecimal(1000);
    public static BigDecimal bd100 = new BigDecimal(100);
    public static BigDecimal bd10 = new BigDecimal(10);

    /**
     *
     * 功能描述: <br>
     * 获取文件，如果没有则创建
     *
     * @param path
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static File gFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /** 将一个 JavaBean 对象转化为一个 Map */
    @SuppressWarnings("rawtypes")
    public static Map<String, Object> beanToMap(Object bean, boolean filterNull) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (bean != null) {
            Class type = bean.getClass();
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(type);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (int i = 0; i < propertyDescriptors.length; i++) {
                    PropertyDescriptor descriptor = propertyDescriptors[i];
                    String propertyName = descriptor.getName();
                    if (!propertyName.equals("class")) {
                        Method readMethod = descriptor.getReadMethod();
                        Object result = readMethod.invoke(bean, new Object[0]);
                        if (result != null) {
                            returnMap.put(propertyName, result);
                        } else if (!filterNull) {
                            returnMap.put(propertyName, result);
                        }
                    }
                }
                LOG.debug("result Map [" + returnMap + "]");
            } catch (Exception e) {
                LOG.error("bean-to->Map error", e);
            }
        }
        return returnMap;
    }

    /** 将一个 JavaBean 对象转化为一个 Map */
    public static Map<String, Object> beanToMap(Object bean) {
        return beanToMap(bean, true);
    }

    public static boolean isPC(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        boolean flag = true;
        if (ua != null) {// iPad
            if (ua.indexOf("iPhone") > -1 || (ua.indexOf("ndroid") > -1 && ua.indexOf("WebKit") > -1)) {
                flag = false;
            }
        }
        return flag;
    }

    public static String getTerminal(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        String flag = "pc";
        if (ua != null) {// iPad
            if (ua.indexOf("iPhone") > -1 || (ua.indexOf("ndroid") > -1 && ua.indexOf("WebKit") > -1)) {
                flag = "mb";
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        // beanToMap(new Result());
    }

    /**
     * 生成随机数字
     *
     * @param length
     * @return
     */
    public static String getRandomNumber(int length) {
        String str = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(9);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/
}
